package com.example.solrdemo.controller;

import com.alibaba.fastjson.JSON;
import com.example.solrdemo.entity.Orders;
import lombok.AllArgsConstructor;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.*;
import org.apache.solr.client.solrj.response.PivotField;
import org.apache.solr.common.params.FacetParams;
import org.apache.solr.common.params.GroupParams;
import org.apache.solr.common.util.NamedList;
import org.springframework.data.domain.Page;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.core.query.*;
import org.springframework.data.solr.core.query.result.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author benjamin_5
 * @Description
 * @date 2023/8/19
 */
@RestController
@RequestMapping("facet")
@AllArgsConstructor
public class FacetSearchController {

    private final HttpSolrClient solrClient;
    private final SolrTemplate solrTemplate;
    /**
     * 统计销量排行前5的商品
     * @return
     */
    @GetMapping("sellTopFive")
    public Map<String, Long> sellTopFive(){
        Map<String, Long> result = new HashMap<>();

        // 设置查询条件
        SolrQuery query = new SolrQuery().setQuery("*:*").setRows(0);
        // 设置分组条件
        query.set(FacetParams.FACET, true)
                .set(FacetParams.FACET_FIELD, "product_name")
                .set(FacetParams.FACET_LIMIT, 5);

        try {
            QueryResponse response = solrClient.query("orders",query);
            FacetField facetFields = response.getFacetField("product_name");
            for (FacetField.Count value : facetFields.getValues()) {
                result.put(value.getName(), value.getCount());
            }

            // 根据value排序
            return result.entrySet().stream()
                    .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
        } catch (SolrServerException | IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    @GetMapping("sellTopFive2")
    public Map<String, Long> sellTopFive2() {
        Map<String, Long> result = new HashMap<>();

        // 设置分组条件
        Field field = new SimpleField("product_name");
        SimpleFacetQuery query = new SimpleFacetQuery(new SimpleStringCriteria("*:*")).setRows(0);
        FacetOptions facetOptions = new FacetOptions()
                .addFacetOnField(field)
                .setFacetLimit(5);
        query.setFacetOptions(facetOptions);

        try {
            FacetPage<Orders> page = solrTemplate.queryForFacetPage("orders", query, Orders.class);

            Page<FacetFieldEntry> pageResult = page.getFacetResultPage("product_name");
            List<FacetFieldEntry> content = pageResult.getContent();
            for (FacetFieldEntry facetFieldEntry : content) {
                result.put(facetFieldEntry.getValue(), facetFieldEntry.getValueCount());
            }

            // 根据数量逆序排序
            return result.entrySet().stream()
                    .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                    .limit(5)
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
        }catch (Exception e){
            e.printStackTrace();
            return result;
        }
    }

    /**
     * 各个标签的订单数
     * @return
     */
    @GetMapping("labelCount")
    public Map<String, Long> labelCount(){
        Map<String, Long> result = new HashMap<>();

        // 设置查询条件
        SolrQuery query = new SolrQuery().setQuery("*:*").setRows(0);
        // 设置分组条件
        query.set(FacetParams.FACET, true)
                .set(FacetParams.FACET_FIELD, "labels")
                .set(FacetParams.FACET_LIMIT, 100);

        try {
            QueryResponse response = solrClient.query("orders",query);
            FacetField facetFields = response.getFacetField("labels");
            for (FacetField.Count value : facetFields.getValues()) {
                result.put(value.getName(), value.getCount());
            }

        } catch (SolrServerException | IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 统计近一年内每月的畅销商品TOP5
     * @return
     */
    @GetMapping("productTopFiveMonthlyNearYear")
    public Map<String, Map<String, Integer>> productTopFiveMonthlyNearYear(){
        Map<String, Map<String, Integer>> result = new TreeMap<>();

        // 设置查询条件
        SolrQuery query = new SolrQuery().setQuery("*:*").setRows(0);
        // 设置分组条件
        query.set(FacetParams.FACET, true)
                .set(FacetParams.FACET_PIVOT, "create_time,product_name")
                .set(FacetParams.FACET_SORT, FacetParams.FACET_SORT_INDEX);

        try {
            QueryResponse response = solrClient.query("orders",query);

            List<PivotField> pivotFields = response.getFacetPivot().get("create_time,product_name");

            // 组装返回结果，按年月分组
            for (PivotField field : pivotFields) {
                SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
                String month = format.format(field.getValue());
                if(!result.containsKey(month)){
                    Map<String, Integer> monthMap = new LinkedHashMap<>();
                    for (PivotField pivotField : field.getPivot()) {
                        monthMap.put(pivotField.getValue().toString(), pivotField.getCount());
                    }
                    result.put(month, monthMap);
                }else{
                    Map<String, Integer> monthMap = result.get(month);
                    for (PivotField pivotField : field.getPivot()) {
                        String productName = pivotField.getValue().toString();
                        if(!monthMap.containsKey(productName)){
                            monthMap.put(productName, pivotField.getCount());
                        }else{
                            // 重复的商品 叠加销量
                            monthMap.put(productName,monthMap.get(productName) + pivotField.getCount());

                        }
                    }
                }
            }
            // 每月商品截取前5
            for (String month : result.keySet()) {
                Map<String, Integer> sortMap = result.get(month).entrySet().stream()
                        .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                        .limit(5)
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
                result.put(month, sortMap);
            }
        } catch (SolrServerException | IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}
